import { getRandom, getCurrentTime } from "@/utils/oss";
import config from "@/config/settings";
import useMultipartOssStore from "@/stores/modules/multipartOssStore";

/**
 * 文件权限
 */
export const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};

/**
 * 根据File文件类型获取后缀
 * @param { File } file
 */
export const getSuffixByFile = (file: File) => {
  const type = file.type;
  if (!type.includes("/")) {
    return "";
  }
  return type.slice(type.lastIndexOf("/") + 1);
};

/**
 * 根据File文件名获取文件名
 * @param { File } file
 */
export const getFilenameByFile = (file: File) => {
  const name = file.name;
  if (!name.includes(".")) {
    return "";
  }
  return name.slice(0, name.lastIndexOf("."));
};

/**
 * 创建新文件名
 */
export const createNewFilename = async (fileData: any) => {
  let objectName = `${config.fileFolder}/${fileData.name}`;
  let file = fileData;
  if (await useMultipartOssStore().isExistObject(objectName)) {
    const fileName = `${getFilenameByFile(fileData)}-${getCurrentTime()}${getRandom()}.${getSuffixByFile(fileData)}`;
    file = new File([fileData], fileName, { type: fileData.type });
    objectName = `${config.fileFolder}/${fileName}`;
  }
  return { file, objectName };
};
